<template>
	<view class="content">
		<Header title="页面标题" targetPage="/pages/changdi_view/changdi_view" index="0" />
		<view class="commit">
			<view class="commit-content " v-if="data">
				<view class="title">
					{{data.name}}
				</view>
				<view class="to-title">
					<p>上午:{{data.am_money}}元/小时</p>
					<p>下午:{{data.pmMoney}}元/小时</p>
					<p>夜间:{{data.nightMoney}}元/小时</p>
				</view>
			</view>
			<!-- 预约时间 -->
			<view class="item yuyue-content" v-if="yuyueList">
				<view class="yuyue-content-itme">
					场地预约记录
				</view>
				<view class="yuyue-content-itme no-vlaue" v-if="!yuyueList[0]">
					<p class="no-vlaue-content">没有预约记录,快去预约吧~</p>
				</view>
				<view class="yuyue-content-itme" v-for="(item,i) in yuyueList" :key="i">
					<view class="right-content">
						<view class="center">
							开始:{{claceTime(item.start_time)}}
						</view>
						<view class="item-content">

						</view>
						<view class="right">
							结束:{{claceTime(item.end_time)}}
						</view>
					</view>
				</view>
			</view>
			<!-- 日期选择器 -->
			<view class="day-content item">
				选择的日期：
				<view class="uni-input">
					<picker mode="date" :value="timeStart.date" :start="getTdayTime()" :end="get3DayTime()"
						@change="bindDateChange">
						<view class="uni-input">{{timeStart.date}}</view>
					</picker>
				</view>
			</view>

			<!-- 选择开始时间 -->
			<view class="start-time-content item">
				选择开始时间：
				<view class="uni-input">
					<picker @change="ChackTimeHour" :value="timeStart.hour.hourData" :range="timeStart.hour.hourData">
						<view class="left">{{ timeStart.hour.hourData[timeStart.hour.checkIndex] }}</view>
					</picker>
					:
					<picker @change="ChackTimeMin" :value="timeStart.min.minData" :range="timeStart.min.minData">
						<view class="right">{{ timeStart.min.minData[timeStart.min.checkIndex] }}</view>
					</picker>
				</view>
			</view>

			<!-- 选择器 -->
			<view class="end-time-content item">
				选择使用时间：
				<view class="uni-input">
					<picker @change="bindChackTimeChange" :value="checkTime.index" :range="checkTime.timeData">
						<view class="">{{checkTime.timeData[checkTime.index]}}</view>
					</picker>
				</view>
			</view>

			<view class="item">
				<input class="uni-input" focus placeholder="输入你的称呼" v-model="userFrom.name" />
			</view>
			<view class="item">
				<input class="uni-input" type="number" placeholder="输入联系电话" v-model="userFrom.tel" />
			</view>
			<view class="check-pay">
				<view class="btn" :class="{ active: checkPayData === 0 }" @click="checkVipCardPay(0)">
					使用微信支付
				</view>
				<view class="btn" :class="{ active: checkPayData === 1 }" @click="checkVipCardPay(1)" v-if="data.isvip == 'True'">
					使用会员卡支付
				</view>

				<view class="btn" @click="gotoVipCard(data.changguan_id)">
					{{data.isvip == 'True'? '充值会员卡':'开通会员卡'}}
				</view>
			</view>
			<view class="vip-card" v-if="data.isvip == 'True'">
				会员卡余额：{{ data.yue }}
			</view>
			<view class="button" @click="yuyue()">
				确认预约
			</view>
		</view>
	</view>
</template>

<script setup>
	import Header from '@/component/topBar.vue';
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app';
	import jsrsasign from 'jsrsasign';
	import {
		ref,
		reactive
	} from 'vue';
	import {
		getYuyueApi,
		getYuyueList,
		getVipyuePay,
		getPay,
		returnPayMessage,
		returnPayMessageFail,
		getOpenId,
		getVipCard
	} from '../../api/api.js';
	import {
		formatDateTime
	} from '../../tools/tools.js';
	// 时间选择
	const timeStart = reactive({
		hour: {
			hourData: [],
			checkIndex: 4 // 初始选择的小时索引
		},
		min: {
			minData: ['00', '30'],
			checkIndex: 0 // 初始选择的分钟索引
		},
		// 日期
		date: '',
		// 保存完整时间
		startTime: '',
		endTime: ''
	});

	const checkTime = reactive({
		timeData: ['1小时', '2小时', '3小时', '4小时', '5小时'],
		index: 0,
		time: 1
	})

	const userFrom = reactive({
		name: '',
		tel: ''
	})

	const data = ref();
	const yuyueList = ref([]);

	// 是否显示vip 余额
	const checkVip = ref(false)
	const vipData = ref(0)
	const checkPayData = ref(0)

	// 选择是否使用会员卡支付
	const checkVipCardPay = (index) => {
		checkPayData.value = index
		console.log('选择代码', checkPayData.value, '传入的代码', index);
	}

	const bindChackTimeChange = (e) => {
		console.log('picker发送选择改变，携带值为', e.detail.value);
		checkTime.index = e.detail.value;
		checkTime.time = Number(e.detail.value) + 1
	};

	// 日期点击事件
	const bindDateChange = (e) => {
		timeStart.date = e.detail.value;
	}

	const ChackTimeHour = (e) => {
		timeStart.hour.checkIndex = e.detail.value;
	};

	const ChackTimeMin = (e) => {
		timeStart.min.checkIndex = e.detail.value;
	};


	// 跳转vip注册
	const gotoVipCard = (changguanId) => {
		uni.navigateTo({
			url: `/views/registeredVipView/registeredVipView?changdiId=${changguanId}`
		})
	}

	// 获取场地预约信息 list
	const __getYuyueList = (id) => {
		getYuyueList(id).then((res) => {
			yuyueList.value = res.values;
			console.log(yuyueList.value);
		});
	};
	// 只获取时间
	const claceTime = (listTime) => {
		let timePart = listTime.split(' ')[1];
		let minutes = listTime.split(':')[1];
		return timePart;
	};
	// 获取2天之后的时间
	const get3DayTime = () => {
		// 获取当前日期
		let currentDate = new Date();
		// 计算三天后的日期
		let futureDate = new Date(currentDate.getTime() + 2 * 24 * 60 * 60 * 1000);
		// 格式化为 YYYY-MM-DD
		let year = futureDate.getFullYear();
		let month = String(futureDate.getMonth() + 1).padStart(2, '0');
		let day = String(futureDate.getDate()).padStart(2, '0');
		return `${year}-${month}-${day}`;
	}

	// 获取当前日期并格式化为 YYYY-MM-DD
	const getTdayTime = () => {
		// 使用 let 保存当前日期
		let currentDate = new Date();
		// 格式化为 YYYY-MM-DD
		let year = currentDate.getFullYear();
		let month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
		let day = String(currentDate.getDate()).padStart(2, '0'); // 日期前补零
		return `${year}-${month}-${day}`;
	}

	// 订阅逻辑 初级校验1
	const yuyue = () => {
		timeStart.startTime = timeStart.date + ' ' + timeStart.hour.hourData[timeStart.hour.checkIndex] + ':' +
			timeStart.min.minData[timeStart.min.checkIndex] + ':00'
		timeStart.endTime = timeStart.date + ' ' + (Number(timeStart.hour.hourData[timeStart.hour.checkIndex]) +
				Number(checkTime.time)) +
			':' + timeStart.min.minData[timeStart.min.checkIndex] + ':00'
		console.log(timeStart.startTime, timeStart.endTime);

		if (userFrom.name === '') {
			uni.showModal({
				title: '提示',
				content: '请输入你的称呼'
			});
		} else if (userFrom.tel === '') {
			uni.showModal({
				title: '提示',
				content: '请输入你的电话'
			});
		} else {

			__getYuyueApi();
		}
	};

	// 预约功能块 确认预约2
	const __getYuyueApi = () => {
		// console.log('预约参数', data.value.id, timeStart.startTime, timeStart.endTime, userFrom.name, userFrom.tel);
		getYuyueApi(data.value.id, timeStart.startTime, timeStart.endTime, userFrom.name, userFrom.tel).then((res) => {
			console.log('预约数据', res);

			if (res.result === 'ok') {
				uni.showToast({
					title: '成功预约',
					icon: 'success', //将值设置为 success 或者 ''
					duration: 4000
				});
				console.log('预约记录', res);
				getCode(res.yuyue_id);
				// 刷新列表
				__getYuyueList(data.value.id);

			} else {
				uni.showModal({
					title: '预约失败',
					content: `${res.result}`,
				});
				// 刷新列表
				__getYuyueList(data.value.id, data.value.money);
			}
		});
	};

	// 支付流程
	const getCode = (yuyueid, money) => {
		uni.login({
			provider: "weixin",
			onlyAuthorize: true, // 微信登录仅请求授权认证
			success: function(code) {
				let miaoshu = `时长:${checkTime.time} 小时,预约ID${yuyueid},时间:${timeStart.date} 时间段：${timeStart.startTime}到${timeStart.endTime}`;
				console.log('支付参数', data.value.id, code.code, miaoshu, timeStart.startTime, checkTime.time,
					'微信支付',
					Number(data.value.changguan_id));

				let payDataJson = {
					changdi: data.value.id,
					code: code.code,
					miaoshu: miaoshu,
					startTime: timeStart.startTime,
					hour: checkTime.time,
					changguanId: Number(data.value.changguan_id),
					timeutc: Math.floor(Date.now() / 1000)
				}

				console.log(payDataJson);

				// 微信支付
				if (checkPayData.value == 0) {
					getPay(payDataJson, '微信支付').then((
						res) => {
						console.log('微信支付参数', res);
						// 调起微信支付
						let miaoshu = `时长:${checkTime.time} 小时,预约id:${yuyueid},金额:${res.total_no / 100}`;
						if (res) {
							// 计算金额并生成描述
							let amountInYuan = Number(money) / 100;
							uni.requestPayment({
								provider: 'wxpay', // 服务提供商
								appid: res.appid,
								timeStamp: res.timeStamp.toString(),
								nonceStr: res.nonceStr, // 随机字符串
								package: res.package,
								signType: 'RSA', // 签名算法
								paySign: res.paySign, // 签名
								success: function(kon) {
									// 支付成功后的业务逻辑
									returnPayMessage(data.value.id, res.out_trade_no,
											res.total_no / 100,
											yuyueid, miaoshu, res.timeStamp, res.openid
										)
										.then((res) => {
											uni.showModal({
												title: '提示',
												content: '您已经预约成功 '
											})
											__getYuyueList(data.value.id);
										})
								},
								fail: function(err) {
									console.log('支付失败', err);
									returnPayMessageFail(yuyueid).then((res) => {
										console.log(res);
										__getYuyueList(data.value.id);
										uni.showModal({
											title: '提示',
											content: res.result
										});
									})
								},
							});
						}
					}).catch((error) => {
						console.error('获取 OpenId 失败', error);
					});
				}
				// 会员卡支付
				else if (checkPayData.value == 1) {
					getVipyuePay(payDataJson, '余额支付', yuyueid).then((res) => {
						if (res.result == 'VIP预约付费成功。') {
							
							
							console.log('余额支付成功', res);
							__getYuyueList(data.value.id);
						} else {
							__getYuyueList(data.value.id);
							uni.showModal({
								title: '提示',
								content: res.result
							});
						}
					})
				}
			},
			fail: function(err) {
				console.error('登录失败', err);
			}
		});
	};

	onLoad((option) => {
		data.value = option;
		
		let splitArray = data.value.time.split(',');
		for (let i = 0; i < splitArray.length; i++) {
			timeStart.hour.hourData.push(splitArray[i]);
		}
		console.log('上级传入的数据', option, '时间', option.time);
		__getYuyueList(option.id)
		timeStart.date = getTdayTime()

	});
</script>

<style lang="scss">
	.content {
		background-color: #f7f7f7;
		min-height: 100vh;
		font-size: 14px;

		.top {
			font-size: 26px;
		}

		.commit {
			padding: 10px;



			.commit-content {
				padding: 10px;
				background-color: #ffffff;
				border-radius: 6px;

				.title {
					width: 100%;
					margin-bottom: 6px;
					font-size: 20px;
				}

				.to-title {
					font-size: 14px;
				}

			}

			.start-time-content {
				.uni-input {
					display: flex;

					.left {
						margin-right: 14px;
					}

					.right {
						margin-left: 14px;
					}
				}

			}

			.yuyue-content {
				justify-content: column;
				flex-wrap: wrap;
				font-size: 12px;



				.yuyue-content-itme {
					padding: 4px;
					width: 100%;
					display: flex;

					.left {
						margin-right: 20px;
						padding: 4px;
					}

					.right-content {
						display: flex;
						flex-wrap: nowrap;
						width: 100%;
						text-align: center;

						.center {
							width: 50%;
							margin-right: 2px;
							padding: 4px;
							border-radius: 12px;
							border: 1px solid #67C23A;
							color: white;
							background-color: #67C23A;
						}

						.item-content {
							margin-top: 12px;
							width: 10px;
							height: 1px;
							background-color: black;
						}

						.right {
							width: 50%;
							padding: 4px;
							border-radius: 12px;
							margin-left: 2px;
							border: 1px solid #F56C6C;
							color: white;
							background-color: #F56C6C;
						}
					}
				}

				.no-vlaue {
					width: 100%;
					padding: 40px 0;
					display: flex;
					justify-content: center;

					.no-vlaue-content {
						font-size: 16px;
					}

				}
			}

			.item {
				margin-top: 10px;
				display: flex;
				padding: 10px;
				background-color: #ffffff;
				border-radius: 6px;
			}

			.uni-input {
				margin-left: 10px;
			}

			.item2 {
				margin: 0 auto;
				justify-content: center;
			}

			.check-pay {
				display: flex;
				justify-content: space-evenly;
				padding: 0 10px;
				margin-top: 10px;
				background-color: #ffffff;
				border-radius: 6px;

				.btn {
					padding: 10px;
				}

				.active {
					color: red;
					font-weight: 700;
				}
			}

			.vip-card {
				padding: 0 10px;
				margin-top: 10px;
				background-color: #ffffff;
				border-radius: 6px;
				padding: 10px 20px;
			}

			.button {
				text-align: center;
				padding: 20px;
				margin-top: 10px;
				border-radius: 6px;
				background-color: #50d3ff;
				color: white;
			}
		}
	}
</style>




[
	//子选项
	{
		'day':'10-1',
		// 当前日期下的子选项
		'data':[
			{
				'time':'时间',
				'isbooking':'未预约',
				'money':金额
			}
		]
	},
	{
		'day':'10-2',
		'data':[
			{
				'time':'时间',
				'isbooking':'未预约',
				'money':金额
			}
		]
	},{
		'day':'10-3',
		'data':[
			{
				'time':'时间',
				'isbooking':'未预约',
				'money':金额
			}
		]
	}
]


<!-- 列表内容 -->
		<view class="list-contert">
			<view class="item-content">
				<view class="item1" @click="gotoVipCard()">
					<p>我的会员卡</p>
					<p>></p>
				</view>
				<view class="item1" >
					<p>待使用</p>
					<p>></p>
				</view>
				<view class="item1" @click="gotoHistoryList()">
					<p>历史订单</p>
					<p>></p>
				</view>
				<view class="item1" @click="gotoChangGuanLogin()">
					<p>场馆入驻</p>
					<p>></p>
				</view>
				<view class="item2">
					<p>更多功能，敬请期待</p>
					<p>></p>
				</view>
			</view>
		</view>